﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using SysManage.BLL;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.BaseInfo;
using ZHDJ.Data.Models.Edu;
using ZHDJ.WebPage;

namespace SysManage.Module.Edu
{
    public partial class PartyEduLessonEdit : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyEduCoursewareAdd";
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }
        private void BindData()
        {
            ControlBusiness.ControlBindDataDictionary(rblFlags, SysDataDictionary.ArticleFlags);
            ControlBusiness.ControlBindDataDictionary(ddlCategory, SysDataDictionary.EduThemeCategory);
            Grid1.PageSize = ConfigHelper.PageSize;
            rblFlags.SelectedIndex = 0;
            hdFileId.Text = StringHelper.NewID;

            string openUrl = String.Format("PartyEduCoursewareSelectEdit.aspx?Lessonid=<script>encodeURIComponent({0})</script>", hdFileId.GetValueReference());

            Button1.OnClientClick = Window1.GetSaveStateReference(hdCurrentSelected.ClientID)
                + Window1.GetShowReference(openUrl);

        }
        private void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                hdFileId.Text = id;
                PartyEduLesson current = DB.PartyEduLessons.Find(id);
                if (current == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                txtTitle.Text = current.Title;

                ddlCategory.SelectedValue = current.Category;

                rblFlags.SelectedValue = current.Flags.ToString();
                cbxEnabled.Checked = current.Status == 4;
            }
            else
            {
                //hdFileId.Text = StringHelper.NewID;
            }
            LoadImageList();
            //dfsd.OnClientClick=  Window1.GetShowReference("../../../share/ImagePreview.aspx?id=" , "图片预览")+"return false;";
            LoadCoursewareList();
        }

        public void LoadImageList()
        {
            var q = from t in DB.PartyEduLessonsImages
                    join u in DB.PartyFiles on t.FileID equals u.ID
                    where t.LessonID == hdFileId.Text
                select new PartyEduLessonImageViewModel()
                {Title=u.Title, FileID=t.FileID, ID=t.ID, OrderNo=t.OrderNo, FileType=t.FileType};
            Grid1.RecordCount = q.Count();
            Grid1.DataSource = q;
            Grid1.DataBind();
        }

        public void LoadCoursewareList()
        {
            //Grid1.RecordCount = q.Count();
            Grid2.DataSource = PartyEduLesson.GetEduCoursewarebyLessonId(hdFileId.Text);
            Grid2.DataBind();
        }

        #endregion

        #region Events

        private void SaveData()
        {
            PartyEduLesson item;
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                //更新
                item = DB.PartyEduLessons.Find(id);
                if (item == null)
                {
                    Alert.Show("参数错误！", String.Empty);
                    return;
                }
                item.ModifyTime = DateTime.Now;
                item.ModifyBy = CurrentUser.ID;
            }
            else
            {

                item = new PartyEduLesson();
                item.ID = hdFileId.Text;
                item.CreateTime = DateTime.Now;
                item.CreateBy = CurrentUser.ID;
                item.ModifyTime = DateTime.Now;
                item.ModifyBy = CurrentUser.ID;
                item.Module = "PartyEduLesson";
                DB.PartyEduLessons.Add(item);
            }
            item.Title = txtTitle.Text;

            item.Category = ddlCategory.SelectedValue;


            item.Flags=Convert.ToInt32(rblFlags.SelectedValue);
            item.Status = cbxEnabled.Checked ? 4 : 1;

            DB.SaveChanges();
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();

            //Alert.Show("添加成功！", String.Empty, ActiveWindow.GetHidePostBackReference());

        }



        /// <summary>
        /// 介绍图片上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "PartyEduLesson-image", SysEnum.UploadFileType.uploadimage);
            if (rs.IsSuccess)
            {
                var image = new PartyeduLessonimage()
                {
                    ID = StringHelper.NewID,
                    LessonID = hdFileId.Text,
                    Status = 4,
                    FileID = rs.FileID,
                    FileType = 2,
                    OrderNo = 0,
                    CreateTime = DateTime.Now,
                    CreateBy = CurrentUser.ID,
                    ModifyTime = DateTime.Now,
                    ModifyBy = CurrentUser.ID
                };
                DB.PartyEduLessonsImages.Add(image);
                DB.SaveChanges();
                LoadImageList();
                Alert.Show("上传成功！", String.Empty);
            }
            else
            {
                Alert.Show("上传失败！" + rs.Message, String.Empty);
            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string PartyEduCoursewareImageId = GetSelectedDataKeyID(Grid1);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPower("PartyEduCoursewareDelete"))
                {
                    CheckPowerFailWithAlert();
                    return;
                }
                var del = DB.PartyEduLessonsImages.FirstOrDefault(t => t.ID == PartyEduCoursewareImageId);
                DB.PartyEduLessonsImages.Remove(del);
                DB.SaveChanges();
               
            }
            else if (e.CommandName == "Cover")
            {
                PartyEduCoursewareImage.SetCover(PartyEduCoursewareImageId,hdCoursewareID.Text);
               
            }
            LoadImageList();
        }

        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            var row = e.DataItem as PartyEduLessonImageViewModel;
            var btnImagePreview = Grid1.FindColumn("btnImagePreview") as LinkButtonField;
           
            if (btnImagePreview != null)
            {
                btnImagePreview.OnClientClick = Window1.GetShowReference("../../../share/ImagePreview.aspx?id="+ row.FileID,"图片预览");
            }

            //封面
            var CoverField = Grid1.FindColumn("CoverField") as LinkButtonField;
            if (CoverField != null && row.FileType == 4)
            {
                CoverField.Enabled = false;
            }
            else
            {
                CoverField.Enabled = true;
            }
        }

        #endregion
        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            LoadCoursewareList();
        }

        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            string relationid = GetSelectedDataKeyID(Grid2);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                //if (!CheckPower("PartyEduCoursewareDelete"))
                //{
                //    CheckPowerFailWithAlert();
                //    return;
                //}
                var del = DB.PartyeduLessonCourseRelations.FirstOrDefault(t => t.ID == relationid);
                DB.PartyeduLessonCourseRelations.Remove(del);
                DB.SaveChanges();

            }
            LoadCoursewareList();
        }

        protected void Grid2_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {

        }
    }
    public class PartyEduLessonImageViewModel
    {
        public string ID { get; set; }
        public string FileID { get; set; }
        public string Title { get; set; }
        public int OrderNo { get; set; }
        public int FileType { get; set; }
    }
}
